package com.nb.service.impl;

import com.nb.dto.nurse.AssistTreatmentDTO;
import com.nb.dto.nurse.NurseInfoDTO;
import com.nb.entity.NursingRecord;
import com.nb.exception.BaseException;
import com.nb.mapper.NurseMapper;
import com.nb.mapper.PatientMapper;
import com.nb.service.NurseService;
import com.nb.utils.CurrentHolderUtil;
import com.nb.vo.nurse.AllPatientInfoVO;
import com.nb.vo.nurse.NeedHelpVO;
import com.nb.vo.nurse.NurseInfoVO;
import com.nb.vo.patient.OrderVO;
import com.nb.utils.FileUploadUtil;
import com.nb.utils.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern; // Import Pattern

@Slf4j
@Service
public class NurseServiceImpl implements NurseService {

    @Autowired
    private NurseMapper nurseMapper;

    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    // Regex to validate pressure format like "120/80"
    private static final Pattern PRESSURE_PATTERN = Pattern.compile("^\\d{1,3}/\\d{1,3}$");


    @Override
    public List<AllPatientInfoVO> getAllPatientInfo() {
        List<AllPatientInfoVO> allPatientInfoList = nurseMapper.getAllPatientInfoList();
        return allPatientInfoList;

    }

    @Override
    public List<NeedHelpVO> getNeedHelpList() {
        List<NeedHelpVO> needHelpList = nurseMapper.getNeedHelpList();
        return needHelpList;
    }

    @Override
    public NurseInfoVO getNurseInfo() {
        // 从线程中获取当前登录的用户ID
        Integer userId = CurrentHolderUtil.getCurrentId();
        // 根据用户ID查询护士信息
        NurseInfoVO nurseInfo = nurseMapper.getNurseInfoById(userId);
        
        // 处理头像URL
        if (nurseInfo != null && nurseInfo.getAvatar() != null) {
            nurseInfo.setAvatar(UrlUtil.buildFullUrl(nurseInfo.getAvatar()));
        }
        
        return nurseInfo;
    }

    @Override
    public void updateNurseInfo(NurseInfoDTO nurseInfoDTO) {
        nurseMapper.updateNurseInfo(nurseInfoDTO);
        log.info("护士信息更新成功，ID: {}", nurseInfoDTO.getId());
    }

    @Transactional
    @Override
    public void assistTreatment(AssistTreatmentDTO dto) {
        Integer userId = CurrentHolderUtil.getCurrentId();
        if (userId == null) {
            throw new BaseException("无法获取当前用户信息");
        }

        // 1. 获取护士ID
        Integer nurseId = nurseMapper.getNurseIdByUserId(userId);
        if (nurseId == null) {
            throw new BaseException("当前用户不是护士或护士信息不存在");
        }

        // 2. 获取患者ID
        Integer patientId = dto.getId();
        if (patientId == null) {
            throw new BaseException("患者ID不能为空");
        }

        // 3. 获取与患者关联的最新已就诊订单ID (或根据业务逻辑选择合适的订单)
        Integer orderId = nurseMapper.getLatestVisitedOrderIdByPatientId(patientId);
        if (orderId == null) {
            throw new BaseException("未找到该患者对应的已就诊订单信息");
        }

        // 4. 验证血压格式 (如果提供了)
        String pressure = dto.getPressure();
        if (StringUtils.hasText(pressure)) {
            if (!PRESSURE_PATTERN.matcher(pressure.trim()).matches()) {
                 throw new BaseException("血压格式不正确，应为 '收缩压/舒张压' (例如 '120/80')");
            }
            pressure = pressure.trim(); // Trim whitespace
        }


        // 5. 构建护理记录对象
        NursingRecord nursingRecord = NursingRecord.builder()
                .orderId(orderId)
                .nurseId(nurseId)
                .patientId(patientId)
                .temperature(dto.getTemperature())
                .pulse(dto.getRate()) // 假设 rate 对应 pulse
                .pressure(pressure) // Store the pressure string directly
                .createTime(LocalDateTime.now())
                .build();

        // 6. 插入护理记录
        nurseMapper.insertNursingRecord(nursingRecord);
        
        // 7. 更新订单护理状态为已诊疗
        nurseMapper.updateOrderNursingStatus(orderId);
        
        log.info("护士 {} 为患者 {} (订单 {}) 添加了生命体征记录，并更新了护理状态", nurseId, patientId, orderId);

    }

    @Override
    public void pay(String id) {
        patientMapper.updateOrderStatusById(id);

    }

    @Override
    public List<OrderVO> getAllOrders() {
        List<OrderVO> ordersList = nurseMapper.getAllOrdersList();

        return ordersList;    }

    @Transactional // 添加事务管理
    @Override
    public String changeAvatar(MultipartFile file) {
        // 1. 获取当前登录用户ID
        Integer userId = CurrentHolderUtil.getCurrentId();
        if (userId == null) {
            throw new BaseException("无法获取当前用户信息，请重新登录");
        }

        // 2. 使用 FileUploadUtil 保存图片
        // 使用 userId 作为文件名的一部分，增加可读性
        String relativePath = fileUploadUtil.saveImage(file, userId);

        // 3. 更新数据库中的头像路径
        int updatedRows = nurseMapper.updateUserAvatar(userId, relativePath);
        if (updatedRows == 0) {
            // 可以选择抛出异常或记录日志，取决于业务需求
            log.warn("更新用户 {} 的头像失败，可能用户不存在", userId);
            // 如果需要严格保证更新成功，可以抛出异常
            // throw new BaseException("更新头像失败");
        } else {
            log.info("用户 {} 的头像更新成功，新路径: {}", userId, relativePath);
        }

        // 4. 返回新的头像访问路径（完整URL）
        return UrlUtil.buildFullUrl(relativePath); // 确保返回完整 URL
    }
}
